package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gorpc"
)

// EchoService 是一个简单的回声服务示例
type EchoService struct{}

// OnConnect 处理连接事件
func (s *EchoService) OnConnect(session *gorpc.RPCSession) {
	fmt.Printf("Client connected: %s\n", session.GetID())

	// 客户端连接后，服务器向客户端发起 RPC 调用
	inMsg := gorpc.NewMessage()
	inMsg.SetMessageID("server_hello")
	inMsg.SetMessage([]byte("Hello from server!"))

	outMsg := gorpc.NewMessage()
	err := session.CallMethod(inMsg, outMsg, 5*time.Second)
	if err != nil {
		fmt.Printf("Server Call error: %v\n", err)
	} else {
		fmt.Printf("Server Call success, response: %s\n", string(outMsg.GetMessage()))
	}
}

// OnClose 处理关闭事件
func (s *EchoService) OnClose(session *gorpc.RPCSession, code int, reason string) {
	fmt.Printf("Client disconnected: %s, code: %d, reason: %s\n", session.GetID(), code, reason)
}

// OnRequest 处理请求
func (s *EchoService) OnRequest(session *gorpc.RPCSession, inMsg *gorpc.RPCMessage, outMsg *gorpc.RPCMessage, timeout time.Duration) error {
	fmt.Printf("Received request: %s, data: %s\n", inMsg.GetMessageID(), string(inMsg.GetMessage()))

	// 简单回显收到的数据
	response := fmt.Sprintf("Echo: %s", string(inMsg.GetMessage()))
	outMsg.SetMessage([]byte(response))
	return nil
}

// OnNotify 处理通知
func (s *EchoService) OnNotify(session *gorpc.RPCSession, msg *gorpc.RPCMessage) {
	fmt.Printf("Received notification: %s, data: %s\n", msg.GetMessageID(), string(msg.GetMessage()))
}

// OnMessage 处理原始消息
func (s *EchoService) OnMessage(session *gorpc.RPCSession, msgType int, data []byte) {
	fmt.Printf("Received raw message: type=%d, data=%s\n", msgType, string(data))
}

func runServer() {
	// 创建服务器实例
	srv := gorpc.NewRPCServer(":8080", &EchoService{})

	// 启动服务器
	if err := srv.Start(); err != nil {
		fmt.Printf("Failed to start server: %v\n", err)
		return
	}

	fmt.Println("Server started on :8080")

	// 等待中断信号以优雅地关闭服务器
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	fmt.Println("Shutting down server...")
	srv.Stop()
	fmt.Println("Server shutdown complete")
}

func main() {
	runServer()
}
